from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import User, Category, News
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET

@profile_blu.route('/other_news_list')
@user_login_data
def other_news_list():
    user = g.user

    page = request.args.get('p',1)
    user_id = request.args.get('user_id')

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    if not all([page,user_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    try:
        other_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    if not other_user:
        abort(404)


    current_page = 1
    total_page = 1
    news_li = []

    try:
        paginate = News.query.filter(News.user_id == other_user.id).paginate(page,constants.OTHER_NEWS_PAGE_MAX_COUNT,False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_dict())

    data = {
        "current_page":current_page,
        "total_page":total_page,
        "news":news_dict_li

    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    user = g.user

    user_id = request.args.get('id')

    if not user_id:
        abort(404)
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)
    is_followed = False
    if user:
        if user.followed.filter(User.id == other.id).count() > 0:
            is_followed = True





    data = {
        "is_followed":is_followed,
        "user":user.to_dict(),
        "other":other.to_dict()
    }
    return render_template("news/other.html",data=data)




@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    page = request.args.get("p",1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    follows = []
    current_page = 1
    total_page = 1
    try:

        paginate = user.followed.paginate(page,constants.USER_FOLLOWED_MAX_COUNT,False)
        current_page = paginate.page
        total_page = paginate.pages
        follows = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    follows_dict_li = []

    for follow in follows:
        follows_dict_li.append(follow.to_dict())

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    user = g.user
    page = request.args.get('p',1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    total_page = 1
    current_page = 1
    news_list = []
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        total_page = paginate.pages
        current_page = paginate.page
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_dict_li
    }

    return render_template("news/user_news_list.html",data=data)


@profile_blu.route('/news_release',methods=["GET","POST"])
@user_login_data
def news_release():
    if request.method == "GET":
        categorys = []
        try:
            categorys = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        categorys_dict_li = []
        for category in categorys:
            categorys_dict_li.append(category.to_dict())

        categorys_dict_li.pop(0)

        return render_template("news/user_news_release.html",data={"categorys":categorys_dict_li})

    # 1. 获取要提交的数据
    # 标题
    title = request.form.get("title")
    # 新闻来源
    source = "个人发布"
    # 摘要
    digest = request.form.get("digest")
    # 新闻内容
    content = request.form.get("content")
    # 索引图片
    index_image = request.files.get("index_image")
    # 分类id
    category_id = request.form.get("category_id")

    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        key = storage(image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 读取图片
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="OK")

@profile_blu.route('/collection')
@user_login_data
def user_collection():
    # 获取参数
    # page = request.args.get("p", 1)
    #
    # # 判断参数
    # try:
    #     page = int(page)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     page = 1
    #
    # # 查询用户指定页数的收藏的新闻
    # user = g.user
    #
    # news_list = []
    # total_page = 1
    # current_page = 1
    # try:
    #     paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
    #     current_page = paginate.page
    #     total_page = paginate.pages
    #     news_list = paginate.items
    # except Exception as e:
    #     current_app.logger.error(e)
    #
    # news_dict_li = []
    # for news in news_list:
    #     news_dict_li.append(news.to_basic_dict())
    #
    # data = {
    #     "total_page": total_page,
    #     "current_page": current_page,
    #     "collections": news_dict_li
    # }
    #
    # return render_template('news/user_collection.html', data=data)
    user = g.user

    page = request.args.get("p",1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    list_dict_li = []
    for new in news_list:
        list_dict_li.append(new.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "collections": list_dict_li
    }

    return render_template("news/user_collection.html",data=data)


@profile_blu.route('/pass_info',methods=["GET","POST"])
@user_login_data
def pass_info():

    user = g.user
    if request.method == "GET":
        return render_template("news/user_pass_info.html",data={"user":user.to_dict()})

    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR,errmsg="原密码错误")

    user.password = new_password

    return jsonify(errno=RET.OK, errmsg="保存成功")




@profile_blu.route('/pic_info',methods=["GET","POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})

    try:
        avatar = request.files.get('avatar')
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    try:
        key = storage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user.avatar_url = key

    return jsonify(errno=RET.OK,errmsg="OK",data={"avatar_url":constants.QINIU_DOMIN_PREFIX + key})

@profile_blu.route('/base_info',methods=["GET","POST"])
@user_login_data
def base_info():
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user": g.user.to_dict()})

    signature = request.json.get('signature')
    nick_name = request.json.get('nick_name')
    gender = request.json.get('gender')

    if not all([signature,nick_name,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    if gender not in ["WOMAN","MAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user = g.user

    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

        # 将 session 中保存的数据进行实时更新
    session["nick_name"] = nick_name
    return jsonify(errno=RET.OK,errmsg="OK")


@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect('/')
    data = {"user":user.to_dict()}
    return render_template("news/user.html",data=data)